package com.xuz.step3;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @user 65453
 * @date 2024/12/9 21:18
 */
public class Step3Server {

    ServerSocket serverSocket;

    IHandlerInterface httpHandler;

    public Step3Server(IHandlerInterface httpHandler) {
        this.httpHandler = httpHandler;
    }
    public void listen(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        while (true) {
            this.accept();
        }
    }

    private void accept() throws IOException {
        Socket socket = serverSocket.accept();
        new Thread(() -> {
            try {
                this.handler(socket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    private void handler(Socket socket) throws IOException {
        Request request = new Request(socket);
        Response response = new Response(socket);
        this.httpHandler.handler(request, response);
    }

    public static void main(String[] args) throws IOException {
        Step3Server server = new Step3Server((request, response) -> {
//            response.send("Greetings\n");
            System.out.println(request.getHeaders());
            response.send("<html><body><h1>Hello world!</h1></body></html>");
        });

        server.listen(8001);
    }
}
